#include "moreitemwidget.h"
#include "libs/core/model/attention.h"
#include "libs/core/model/attentionmodel.h"
#include "libs/core/model/model.h"
#include "liverecorder.h"
#include "liverecorderview.h"
#include "yingce.h"
#include <QHBoxLayout>
#include <QIcon>
#include <QMenu>
#include <QToolButton>

MoreItemWidget::MoreItemWidget(LiveRecorderView* view, const yc::Attention* attention,
                               QWidget* parent)
    : QWidget { parent }, view_(view), id_(attention->id)
{
    auto recorder = qobject_cast<LiveRecorder*>(view_->extension());

    QHBoxLayout* hl = new QHBoxLayout(this);
    hl->setContentsMargins(0, 0, 0, 0);
    hl->setSpacing(4);
    hl->addStretch(1);

    QAction* auto_record_action = new QAction(this);
    auto_record_action->setCheckable(true);
    auto_record_action->setChecked(attention->auto_record);
    auto_record_action->setIcon(recorder->autoRecordAction()->icon());
    auto_record_action->setText(recorder->autoRecordAction()->text());
    auto_record_action->setToolTip(recorder->autoRecordAction()->toolTip());

    QToolButton* auto_record_button = new QToolButton(this);
    auto_record_button->setCheckable(true);
    auto_record_button->setDefaultAction(auto_record_action);
    hl->addWidget(auto_record_button);

    QIcon icon;
    icon.addFile(QString::fromLatin1(":/images/more.png"), QSize(), QIcon::Normal, QIcon::Off);
    QAction* more_action = new QAction(icon, tr("More"), this);

    QToolButton* more_button = new QToolButton(this);
    more_button->setObjectName("more");
    more_button->setDefaultAction(more_action);
    hl->addWidget(more_button);

    connect(auto_record_action, &QAction::triggered, this, [this](bool checked) {
        auto recorder = qobject_cast<LiveRecorder*>(view_->extension());
        view_->setCurrentAttention(id_);
        recorder->autoRecordAction()->trigger();
        if (auto a = YingCe::instance()->model()->attentionModel()->attention(id_)) {
            auto auto_record_action = qobject_cast<QAction*>(sender());
            auto_record_action->setChecked(a->auto_record);
        }
    });
    connect(more_action, &QAction::triggered, this, [this, more_button](bool checked) {
        Q_UNUSED(checked)
        auto recorder = qobject_cast<LiveRecorder*>(view_->extension());
        view_->setCurrentAttention(id_);
        QMenu* more_menu = new QMenu(this);
        more_menu->addAction(recorder->openDirAction());
        more_menu->addAction(recorder->homeAction());
        auto mpos = more_button->contentsRect().bottomRight();
        mpos.setX(mpos.x() - more_menu->sizeHint().width());
        more_menu->exec(more_button->mapToGlobal(mpos));
    });
}
